//index.js
//获取应用实例
const app = getApp()
var template = require('../../template/template.js');
Page({
  data: {
    pages: 1,
    sections: [{
        "name": "国内",
        "active": true
      },
      {
        "name": "国际",
        "active": false
      },
    ],
    news: []
  },
  onLoad: function() {
    template.tabbar("tabBar", 0, this) //0表示第一个tabbar

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    };
    var that = this
    wx.request({
      url: 'http://39.104.106.212/index/chinese',
      method: 'post',
      data: {
        'page': that.data.pages
      },
      success: function(res) {
        that.setData({
          news: res.data.data
        })
      }
    })
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  onSectionClicked: function(e) {
    var sid = e.currentTarget.dataset.sid;
    //刷新选中状态
    for (var i in sectionData) {
      if (sectionData[i]['section_id'] == sid) {
        sectionData[i]['active'] = true
        currentSectionIndex = i
      } else
        sectionData[i]['active'] = false
    }
    this.setData({
      sections: sectionData
    });
  },

  onReachBottom: function() {
    var that = this;
    // 显示加载图标
    wx.showLoading({
      title: '玩命加载中',
    })
    // 页数+1
    var page = undefined
    page = that.data.pages + 1;
    console.log(page)
    wx.request({
      url: 'http://39.104.106.212/index/chinese',
      method: "POST",
      data: {
        'page': page
      },
      success: function(res) {
        // 回调函数
        var new_news = that.data.news;

        for (var i = 0; i < res.data.data.length; i++) {
          new_news.push(res.data.data[i]);
        }
        // 设置数据
        that.setData({
          news: new_news,
          pages: page
        })
        // 隐藏加载框
        wx.hideLoading();
      }
    })
  }
})